/**
 * 规则详情
 */
define([ '../../common/service',  'codeMirror', 'groovy', 'python'],function(http,CodeMirror){
     var RuleScriptDetail = {
         init : function(){
            var _this = this;
             _this.initDom();
             _this.loadDetail();
             _this.ruleEngineEvent();
             _this.bindSaveEvent();
             _this.bindSelectPointEvent();
             _this.initSelectPointModal();
             _this.bindTestEvent();
         },
         initDom : function(){
             var _this = this;
             _this.initDataCycle(0, 90);
             _this.initSnapCycle(0, 90);
             $(".container-fluid").removeClass("hide");
             _this.initDaterangepicker();
         },
         /**
          * 初始化数据周期
          * @param min
          * @param max
          */
         initDataCycle: function(min, max) {
             var _dataCycle = $('select[name="data-cycle"]'),
                 _tmpHtml = '';
             for (var i = min; i <= max; i++) {
                 _tmpHtml += '<option value="' + i + '">' + i + '</option>';
             }
             _dataCycle.html(_tmpHtml);
             _dataCycle.select2();
         },
         initSnapCycle:function(min, max) {
             var _dataCycle = $('select[name="snap-cycle"]'),
                 _tmpHtml = '';
             for (var i = min; i <= max; i++) {
                 _tmpHtml += '<option value="' + i + '">' + i + '</option>';
             }
             _dataCycle.html(_tmpHtml);
             _dataCycle.select2();
         },
         /**
          * 规则引擎事件
          */
         ruleEngineEvent: function() {
             var _this = this;
             var _ruleEngine = $('select[name="rule-engine"]');
             _ruleEngine.unbind("change");
             _ruleEngine.bind("change", function() {
                 $('#rule-script').val('');
                 _this.codeMirrorInit($(this).val());
             });
             _ruleEngine.trigger("change");
         },
         /**
          * 查看时 回填详细信息
          * @param pageQuery
          */
         loadDetail: function() {
             var _this = this;
             var _id = window.location.search.split('?id=')[1];
             if (_id && Number(_id)) {
                 var loadingArea = $('.container-fluid');
                 //遮罩
                 Kit.loading.show(loadingArea);
                 http.work('/rulescript/detail',{id: _id},'POST').then(function(res){
                     var _versions = $('select[name="versions"]', loadingArea);
                     var _versionsTmpData = {};
                     var _versionsTmpHtml = '';
                     $.each(res.data.versions, function(i, version) {
                         _versionsTmpHtml += '<option value="' + version.id + '">' + version.version + '</option>';
                         _versionsTmpData[version.id] = version;
                     });
                     _versions.html(_versionsTmpHtml);

                     _this.fillData(res.data.rule);

                     //切换版本信息
                     _versions.unbind("change");
                     _versions.bind("change", function() {
                         var ruleScript = _versionsTmpData[$(this).val()];
                         _this.fillData(ruleScript);
                     });

                     Kit.loading.hide(loadingArea);
                 });
             }
         },
         /**
          *回填数据
          */
         fillData: function(rulescript) {
             var _this = this;
             var _ruleScriptPanel = $('.container-fluid');
             //回填信息
             //规则名称
             var _ruleName = $("#rule-name", _ruleScriptPanel);
             _ruleName.val(rulescript.ruleName);
             _ruleName.attr('disabled', 'disabled');

             //规则描述
             var _ruleComment = $("#rule-comment", _ruleScriptPanel);
             _ruleComment.val(rulescript.ruleComment);

             //日数据周期
             var _dataCycle = $('select[name="data-cycle"]', _ruleScriptPanel);
             _dataCycle.val(rulescript.dataCycle || 0).trigger("change");

             //快照数据周期
             var _dataCycle = $('select[name="snap-cycle"]', _ruleScriptPanel);
             _dataCycle.val(rulescript.snapCycle || 0).trigger("change");

             //版本
             var _historyVersions = $("#history-versions", _ruleScriptPanel);
             var _versions = $('select[name="versions"]', _historyVersions);
             _versions.val(rulescript.id);
             _historyVersions.removeClass("hide");

             //是否运行
             $(':radio[name="is-run"]').removeAttr('checked');
             $(':radio[name="is-run"][value="' + rulescript.isRun + '"]', _ruleScriptPanel).prop('checked', 'checked');

             //日志级别
             var _scriptLoggerLevel = $('select[name="script-logger-level"]', _ruleScriptPanel);
             _scriptLoggerLevel.val(rulescript.logLevel);

             //脚本语言
             var _ruleEngine = $('select[name="rule-engine"]', _ruleScriptPanel);
             _ruleEngine.val(rulescript.ruleEngine);

             //忽略数据构建语言
             $('input[name="ignoreDataBuild"]').removeAttr("checked");
             if (rulescript.ignoreDataBuild){
                 var ignoreDataBuilds = rulescript.ignoreDataBuild.split(",");
                 $.each(ignoreDataBuilds, function(i, ignoreDataBuild){
                     $('input[name="ignoreDataBuild"][value="' + ignoreDataBuild + '"]', _ruleScriptPanel).prop("checked", "checked");
                 });
             }

             //规则
             $('#rule-script').val(rulescript.ruleScript);
             _this.codeMirrorInit(rulescript.ruleEngine);
         },
         codeMirrorInit: function(_ruleEngine) {
             var _this = this;
             $(".CodeMirror").remove();
             var edit;
             if (_ruleEngine == 'python') {
                 edit = CodeMirror.fromTextArea(document.getElementById("rule-script"), {
                     lineNumbers: true,
                     matchBrackets: true,
                     extraKeys: {
                         "Alt-/": "autocomplete"
                     },
                     mode: {
                         name: "python",
                         version: 3,
                         singleLineStringErrors: false
                     },
                     indentUnit: 4
                 });
             } else {
                 edit = CodeMirror.fromTextArea(document.getElementById("rule-script"), {
                     lineNumbers: true,
                     matchBrackets: true,
                     extraKeys: {
                         "Alt-/": "autocomplete"
                     },
                     mode: "text/x-groovy",
                     indentUnit: 2
                 });
             }
             _this.edit = edit;
         },
         /**
          * 绑定保存事件
          */
         bindSaveEvent: function() {
             var _this = this;
             var _saveButton = $("#button-save");
             _saveButton.unbind('click');
             _saveButton.bind('click', function(e) {
                 e.preventDefault();
                 //校验
                 var _ruleScriptPanel = $('.container-fluid');
                 //规则名不能为空
                 var _ruleName = $("#rule-name", _ruleScriptPanel);
                 var _ruleNameVal = $.trim(_ruleName.val());
                 if (!_ruleNameVal || _ruleNameVal == '') {
                     _ruleName.val('');
                     Kit.warning(_ruleName);
                     return false;
                 }

                 //规则不能为空
                 var _ruleScriptVal = _this.edit.getValue();;
                 var _ruleScriptTrimVal = $.trim(_ruleScriptVal);
                 if (!_ruleScriptTrimVal || _ruleScriptTrimVal == '') {
                     _this.edit.setValue('');
                     _this.edit.focus();
                     Kit.warning($(".rule-script-area"))
                     return false;
                 }

                 //构造参数
                 var param = {
                     ruleName: _ruleNameVal,
                     ruleComment: $("#rule-comment", _ruleScriptPanel).val(),
                     dataCycle: $('select[name="data-cycle"]', _ruleScriptPanel).val(),
                     snapCycle : $('select[name="snap-cycle"]', _ruleScriptPanel).val(),
                     isRun: $(':radio[name="is-run"]:checked', _ruleScriptPanel).val(),
                     ruleEngine: $('select[name="rule-engine"]', _ruleScriptPanel).val(),
                     logLevel: $('select[name="script-logger-level"]', _ruleScriptPanel).val(),
                     ruleScript: _ruleScriptVal
                 };

                 //忽略数据构建语言
                 var _ignoreDataBuilds = $('input[name="ignoreDataBuild"]:checked');
                 if (_ignoreDataBuilds.length > 0){
                     var ignoreDataBuild = "";
                     var isFirst = true;
                     $.each(_ignoreDataBuilds, function(i, v){
                         if (!isFirst){
                             ignoreDataBuild += ",";
                         }
                         ignoreDataBuild += $(v).val();
                         isFirst = false;
                     });
                     param.ignoreDataBuild = ignoreDataBuild;
                 }

                 _saveButton.attr("disabled", "disabled");
                 http.work('/rulescript/save',param,'POST').then(function(res){
                     //跳转到规则列表页面
                     window.location.hash = '#!rulescriptList';
                     _saveButton.removeAttr("disabled");
                 });
             });
         },
         /**
          * 绑定选择触发点事件
          */
         bindSelectPointEvent: function() {
             var _this = this;
             var _testButton = $("#button-select-point");
             _testButton.unbind('click');
             _testButton.bind('click', function() {
                 var _ruleScriptPanel = $('.container-fluid');
                 var _ruleName = $("#rule-name", _ruleScriptPanel);
                 var _ruleNameVal = $.trim(_ruleName.val());
                 if (!_ruleNameVal || _ruleNameVal == '') {
                     _ruleName.val('');
                     Kit.warning(_ruleName);
                     return false;
                 }

                 var _ruleScriptVal = _this.edit.getValue();
                 var _ruleScriptTrimVal = $.trim(_ruleScriptVal);
                 if (!_ruleScriptTrimVal || _ruleScriptTrimVal == '') {
                     _this.edit.setValue('');
                     _this.edit.focus();
                     Kit.warning($(".rule-script-area"))
                     return false;
                 }

                 var _objectiveId = $("#objective-id", _ruleScriptPanel);
                 var _objectiveIdVal = $.trim(_objectiveId.val());
                 if (!_objectiveIdVal || _objectiveIdVal == '') {
                     _objectiveId.val('');
                     Kit.warning(_objectiveId);
                     return false;
                 }
                 //目标Id必须为数字
                 if (!/^[0-9]{13,13}$/.test(_objectiveIdVal)) {
                     Kit.alert2(I18N.getText("rulescriptDetail","tarIdErrorMsg"));
                     return false;
                 }

                 var hasDatepicker = _ruleScriptPanel.find('#date-period'), //获取时间控件所在的input
                     dataObj = hasDatepicker.data('daterangepicker'); //获取daterangepicker对象
                 if (hasDatepicker.val() == '') {
                     Kit.warning($(".date-area"));
                     return false;
                 }

                 //查询指定时间段内的触发点
                 var param = {
                     objectiveType: $('select[name="objective-type"]', _ruleScriptPanel).val(),
                     objectiveId: _objectiveIdVal,
                     testStartDate: dataObj.startDate.format('YYYY-MM-DD'),
                     testEndDate: dataObj.endDate.format('YYYY-MM-DD')
                 }

                 var _loadingArea = $("#test-div");
                 Kit.loading.show(_loadingArea);
                 _testButton.attr("disabled", "disabled");
                 http.work('/rulescript/listSnapData',param,'POST').then(function(res){
                     var data = res.data;
                     _testButton.removeAttr("disabled", "disabled");
                     Kit.loading.hide(_loadingArea);

                     if (!data || 0 >= data.length) {
                         Kit.alert(I18N.getText("rulescriptDetail","noTriggerPoint"));
                         return false;
                     }

                     _this.renderSnapDataList(data);
                     var selectPointModal= $('#select-point-modal');
                     selectPointModal.trigger( 'scroll' );  //处理chrome 下在弹出前无法触发弹出框内的滚轴事件
                     $(".select-point-container").trigger( 'scroll' );  //处理chrome 下在弹出前无法触发弹出框内的滚轴事件
                     selectPointModal.modal({
                         backdrop: 'static',
                         keyboard: false
                     });

                     selectPointModal.modal('show');
                 });
             });
         },
         renderSnapDataList : function(_snapDatas){
             var _this = this;
             var _tbody = $("#select-point-grid", "#select-point-modal");
             //清空数据
             _tbody.empty();
             var tHtml = '';
             _this.timezoneValue = window.sessionStorage.timezoneValue;
             $.each(_snapDatas, function(i, snapData) {
                 tHtml += '<tr>';
                 var updateDate = moment(snapData.updateTime).utcOffset(_this.timezoneValue).format('YYYY-MM-DD HH:mm:ss');
                 //单选按钮
                 tHtml += '<td>';
                 tHtml += '<label><input type="radio" name="snap" value="' + updateDate + '" class="radiobox"><span></span></label>';
                 tHtml += '</td>';
                 //触发时间点
                 tHtml += '<td>';
                 tHtml += updateDate;
                 tHtml += '</td>';
                 //数据快照
                 tHtml += "<td title='" + JSON.stringify(snapData) + "'>";
                 tHtml += JSON.stringify(snapData);
                 tHtml += '</td>';
                 tHtml += '</tr>';
             });
             _tbody.append(tHtml);
         },
         /*
          @初始化时间控件
          */
         initDaterangepicker: function() {
             var _this = this;
             http.do("/common/timestamp").then(function(rsp) {
                 _this.nowDate = new Date(rsp.data.date);
                 _this.timezoneId = window.sessionStorage.timezoneValue;
                 //存储时区信息至widget属性
                 var datepicker = $('.datepicker');
                 //生成快捷选择时间段
                 //subtract方法会对调用对象进行修改，所以无法将moment(_this.nowDate).utcOffset(_this.timezoneValue)抽取为变量
                 var today = moment(_this.nowDate).utcOffset(_this.timezoneId).format('YYYY-MM-DD'),
                     yesterday = moment(_this.nowDate).utcOffset(_this.timezoneId).subtract(1, 'days').format('YYYY-MM-DD'),
                     forward_7_day = moment(_this.nowDate).utcOffset(_this.timezoneId).subtract(6, 'days').format('YYYY-MM-DD'),
                     forward_30_day = moment(_this.nowDate).utcOffset(_this.timezoneId).subtract(29, 'days').format('YYYY-MM-DD'),
                     thisMonthBegin = moment(_this.nowDate).utcOffset(_this.timezoneId).startOf('month').format('YYYY-MM-DD'),
                     thisMonthEnd = moment(_this.nowDate).utcOffset(_this.timezoneId).endOf('month').format('YYYY-MM-DD'),
                     lastMonthBedin = moment(_this.nowDate).utcOffset(_this.timezoneId).subtract(1, 'month').startOf('month').format('YYYY-MM-DD'),
                     lastMonthEnd = moment(_this.nowDate).utcOffset(_this.timezoneId).subtract(1, 'month').endOf('month').format('YYYY-MM-DD');
                 datepicker.daterangepicker({
                     timezone: _this.timezoneId,
                     locale: {
                         format: 'YYYY-MM-DD',
                         separator:' 至 ',
                         applyLabel: '确定',
                         cancelLabel: '取消',
                         fromLabel: '所在时区：',
                         toLabel: _this.timezoneId,
                         customRangeLabel: '自定义',
                         daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
                         monthNames: ['一月', '二月', '三月', '四月', '五月',
                             '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'
                         ],
                         firstDay: 0
                     },
                     ranges: {
                         '今天': [today, today],
                         '昨天': [yesterday, yesterday],
                         '前七天': [forward_7_day, today],
                         '前三十天': [forward_30_day, today],
                         '本月': [thisMonthBegin, thisMonthEnd],
                         '上月': [lastMonthBedin, lastMonthEnd]
                     },
                     autoUpdateInput: false,
                     autoApply:false,
                     opens:'left',
                     drops:'up',
                     applyClass : 'date-apply'
                 },function (start, end) {
                    var tpl = start.format("YYYY-MM-DD") + I18N.getText('management','to') + end.format("YYYY-MM-DD");
                    $('#date-period').val(tpl);
                 }).val("");

                 datepicker.unbind('keydown');
                 datepicker.keydown(function(e) {
                     return false;
                 });

                 //打开日期控件：添加时区信息
                 datepicker.on('show.daterangepicker', function(){
                     if (0 < $('.date-apply').parent().find('.time-zone').length){
                         return;
                     }
                     var timezoneHtml = '<div class="time-zone" style="color:#f90">'
                         + '<label>'+I18N.getText("rulescriptDetail","inTimeZone")+'</label>'
                         + '<label>' + _this.timezoneId + '</label>'
                         + '</div>';
                     $('.date-apply ').before(timezoneHtml);
                 });
             });
         },
         initSelectPointModal: function(){
             var _this = this;
             //初始化列表
             var settings = ({
                 supportAdjust: true, //是否支持宽度调整
                 supportDrag: false, //是否支持拖拽换位
                 supportConfig: false, //是否支持配置列表功能[操作列是否可见]
                 scrollDOM: '.select-point-container'
             });

             $('table[list-manager="select-point-list"]').listManager('init', settings, function(){});

             //渲染弹出框
             var selectPointModal= $('#select-point-modal');
             //测试（运行事件）
             $("#test-btn", selectPointModal).off("click").on("click", function(){
                 _this.bindModalTestEvent(function() {
                     selectPointModal.modal("hide");
                 });
             });

             //导出事件
             $("#export-btn", selectPointModal).off("click").on("click", function(){
                 _this.bindExportDataEvent(function() {
                     selectPointModal.modal("hide");
                 });
             });
         },
         /**
          * 绑定测试事件
          */
         bindModalTestEvent: function(cb) {
             var _this = this;

             var checked = $(':radio:checked', '#select-point-grid');
             if (!checked.length) {
                 Kit.alert(I18N.getText("rulescriptDetail","selectTriPtForRule"));
                 return false;
             }

             //执行回掉
             typeof(cb) == 'function' ? cb(): '';

             var runTimeVal = checked.val();
             _this.runTimeVal = runTimeVal;
             $('.test-label label').html(I18N.getText("rulescriptDetail","triggerTime")+runTimeVal);
             $('.test-label').removeClass('hide');
             //$('.btn-test').removeClass('hide');
             //清空测试区域
             $("#test-result").html('');

             _this.test(runTimeVal);
         },
         test:function(runTimeVal) {
             var _this = this;
             //构造参数
             var _ruleScriptPanel = $('.container-fluid');
             var _ruleName = $("#rule-name", _ruleScriptPanel);
             var _ruleNameVal = $.trim(_ruleName.val());
             var _ruleScriptVal = _this.edit.getValue();
             var _objectiveId = $("#objective-id", _ruleScriptPanel);
             var _objectiveIdVal = $.trim(_objectiveId.val());

             var param = {
                 ruleName: _ruleNameVal,
                 dataCycle: $('select[name="data-cycle"]', _ruleScriptPanel).val(),
                 snapCycle : $('select[name="snap-cycle"]', _ruleScriptPanel).val(),
                 ruleEngine: $('select[name="rule-engine"]', _ruleScriptPanel).val(),
                 logLevel: $('select[name="script-logger-level"]', _ruleScriptPanel).val(),
                 ruleScript: _ruleScriptVal,
                 objectiveType: $('select[name="objective-type"]', _ruleScriptPanel).val(),
                 objectiveId: _objectiveIdVal,
                 tiggerPointDate: runTimeVal
             };

             //忽略数据构建语言
             var _ignoreDataBuilds = $('input[name="ignoreDataBuild"]:checked');
             if (_ignoreDataBuilds.length > 0){
                 var ignoreDataBuild = "";
                 var isFirst = true;
                 $.each(_ignoreDataBuilds, function(i, v){
                     if (!isFirst){
                         ignoreDataBuild += ",";
                     }
                     ignoreDataBuild += $(v).val();
                     isFirst = false;
                 });
                 param.ignoreDataBuild = ignoreDataBuild;
             }

             //清空测试结果
             var _testResult = $("#test-result");
             _testResult.html('');

             //测试请求
             var _loadingArea = $("#test-div");
             Kit.loading.show(_loadingArea);
             http.work('/rulescript/test',param,'POST').then(function(res){
                 var template;
                 var scriptResultTemp;
                 $.each(res.data, function(i, scriptResult) {
                     scriptResultTemp = {
                         result: scriptResult.result || '',
                         exceptionMsg: scriptResult.exceptionMsg || '',
                         logs: scriptResult.logs || ''
                     };
                     template = _.template($('#test-result-script').text())(scriptResultTemp);
                     _testResult.append(template);
                 });
                 Kit.loading.hide(_loadingArea);
             });
         },
         bindCatalogEvent: function(){
             var _this = this;

             $('.btn-test').off('click').on('click', function() {
                 //校验
                 var _ruleScriptPanel = $('.container-fluid');
                 var _ruleName = $("#rule-name", _ruleScriptPanel);
                 var _ruleNameVal = $.trim(_ruleName.val());
                 if (!_ruleNameVal || _ruleNameVal == '') {
                     _ruleName.val('');
                     Kit.warning(_ruleName);
                     return false;
                 }

                 var _ruleScriptVal = _this.edit.getValue();
                 var _ruleScriptTrimVal = $.trim(_ruleScriptVal);
                 if (!_ruleScriptTrimVal || _ruleScriptTrimVal == '') {
                     _this.edit.setValue('');
                     _this.edit.focus();
                     Kit.warning($(".rule-script-area"))
                     return false;
                 }

                 var _objectiveId = $("#objective-id", _ruleScriptPanel);
                 var _objectiveIdVal = $.trim(_objectiveId.val());
                 if (!_objectiveIdVal || _objectiveIdVal == '') {
                     _objectiveId.val('');
                     Kit.warning(_objectiveId);
                     return false;
                 }

                 //目标Id必须为数字
                 if (!/^[0-9]{13,13}$/.test(_objectiveIdVal)) {
                     Kit.alert2(I18N.getText("rulescriptDetail","tarIdErrorMsg"));
                     return false;
                 }

                 if (!_this.runTimeVal || '' == _this.runTimeVal){
                     Kit.alert2(I18N.getText("rulescriptDetail","selectTriPt"));
                     return false;
                 }

                 _this.test(_this.runTimeVal);
             });
         },
         bindExportDataEvent: function(cb) {
             var _this = this;

             var checked = $(':radio:checked', '#select-point-grid');
             if (!checked.length) {
                 Kit.alert(I18N.getText("rulescriptDetail","selectTriPtForData"));
                 return false;
             }

             typeof(cb) == 'function' ? cb(): '';

             var _ruleScriptPanel = $('.container-fluid');
             var _ruleName = $("#rule-name", _ruleScriptPanel);
             var _ruleNameVal = $.trim(_ruleName.val());
             var _ruleScriptVal = _this.edit.getValue();
             var _objectiveId = $("#objective-id", _ruleScriptPanel);
             var _objectiveIdVal = $.trim(_objectiveId.val());

             var param = {
                 ruleName: _ruleNameVal,
                 dataCycle: $('select[name="data-cycle"]', _ruleScriptPanel).val(),
                 snapCycle : $('select[name="snap-cycle"]', _ruleScriptPanel).val(),
                 ruleEngine: $('select[name="rule-engine"]', _ruleScriptPanel).val(),
                 logLevel: $('select[name="script-logger-level"]', _ruleScriptPanel).val(),
                 ruleScript: '',
                 objectiveType: $('select[name="objective-type"]', _ruleScriptPanel).val(),
                 objectiveId: _objectiveIdVal,
                 tiggerPointDate: checked.val()
             }

             //忽略数据构建语言
             var _ignoreDataBuilds = $('input[name="ignoreDataBuild"]:checked');
             if (_ignoreDataBuilds.length > 0){
                 var ignoreDataBuild = "";
                 var isFirst = true;
                 $.each(_ignoreDataBuilds, function(i, v){
                     if (!isFirst){
                         ignoreDataBuild += ",";
                     }
                     ignoreDataBuild += $(v).val();
                     isFirst = false;
                 });
                 param.ignoreDataBuild = ignoreDataBuild;
             }

             window.location.href =  cors_config.api_host + '/rulescript/exportdata?param=' + escape(JSON.stringify(param));
         }
     }

    return RuleScriptDetail;
});
